package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.AgeGenerator;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住管理Service业务层处理
 *
 * @author zhengsuyang
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住管理
     *
     * @param id 入住管理主键
     * @return 入住管理
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住管理列表
     *
     * @param checkIn 入住管理
     * @return 入住管理
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住管理
     *
     * @param checkIn 入住管理
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住管理
     *
     * @param ids 需要删除的入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住管理信息
     *
     * @param id 入住管理主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int apply(CheckInApplyDto checkInApplyDto) {
        // 老人信息DTO
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        // 入住配置DTO
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        // 入住合同DTO
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        // 老人家属DTO
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        // 入住信息新增
        // 校验老人是否已入住  如果已入住直接抛异常BaseException
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        lambdaQueryWrapper.eq(Elder::getStatus, 4);
        Elder elder  = elderMapper.selectOne(lambdaQueryWrapper);
        if (elder != null) {
            throw new BaseException("该老人已入住");
        }
        // 更新床位的状态
        // 获取床位id
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if (bed==null){
            throw new BaseException("请选择正确的床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateBed(bed);
        // 新增或更新老人elder
        elder = updateOrAddElder(checkInElderDto, bed);
        // 新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
        AddContract(checkInContractDto, elder,checkInConfigDto);
        // 新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = AddCheckIn(elder, checkInConfigDto, elderFamilyDtoList);
        // 新增入住配置
        AddCheckInConfig(checkInConfigDto,checkIn);
        return 1;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 入住详情Vo
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 老人信息Vo
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 入住配置信息 Vo
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        // 获取老人Id
        Long elderId = checkIn.getElderId();
        // 根据老人id查询老人信息
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(AgeGenerator.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        // 家属信息
        String elderFamily = checkIn.getRemark();
        // 转换为elderFamilyVo对象
        List<ElderFamilyVo> familyList = JSONUtil.toList(elderFamily, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(familyList);
        // 入住配置
        LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        // 获取床位号
        String bedNumber = checkIn.getBedNumber();
        // 获取开始时间
        LocalDateTime startDate = checkIn.getStartDate();
        // 获取结束时间
        LocalDateTime endDate = checkIn.getEndDate();
        checkInConfigVo.setBedNumber(bedNumber);
        checkInConfigVo.setStartDate(startDate);
        checkInConfigVo.setEndDate(endDate);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        // 合同
        // 根据老人id查询合同
        LambdaQueryWrapper<Contract> contractQueryWrapper = new LambdaQueryWrapper<>();
        contractQueryWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(contractQueryWrapper);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    /**
     * 新增入住配置
     * @param checkInConfigDto
     * @param checkIn
     */
    private void AddCheckInConfig(CheckInConfigDto checkInConfigDto,CheckIn checkIn) {
        // 创建入住配置实体类
        CheckInConfig checkInConfig = new CheckInConfig();
        // 给入住配置赋值
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelName(checkIn.getNursingLevelName());
        // 新增入住配置信息
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息  老人家属信息存到remark字段中
     * @param elder
     * @param checkInConfigDto
     * @param elderFamilyDtoList
     */
    private CheckIn AddCheckIn(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        // 创建入住信息实体类
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        // 老人家属信息存到remark字段中
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);
        // 新增入住信息
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增合同信息
     *
     * @param checkInContractDto
     * @param elder
     */
    private void AddContract(CheckInContractDto checkInContractDto, Elder elder,CheckInConfigDto checkInConfigDto) {
        // 创建合同实体类
        Contract contract = new Contract();
        // 给合同实体类赋值
        contract.setElderId(elder.getId());
        contract.setContractName(checkInContractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(checkInContractDto.getAgreementPath());
        contract.setThirdPartyPhone(checkInContractDto.getThirdPartyPhone());
        contract.setThirdPartyName(checkInContractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contract.setSignDate(checkInContractDto.getSignDate());
//        contract.setTerminationSubmitter();
//        contract.setTerminationDate();
//        contract.setTerminationAgreementPath();
//        contract.setSortOrder();
        // 新增合同
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人elder
     *
     * @param checkInElderDto
     */
    private Elder updateOrAddElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 根据身份证号查询老人是否存在
        LambdaQueryWrapper<Elder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(lambdaQueryWrapper);
        // 修改老人信息
        if (elder != null) {
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setStatus(4);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }
        else {
            elder = new Elder();
        }
        // 新增老人信息
//        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setName(checkInElderDto.getName());
        elder.setImage(checkInElderDto.getImage());
        elder.setIdCardNo(checkInElderDto.getIdCardNo());
        elder.setSex(checkInElderDto.getSex());
        elder.setStatus(4);
        elder.setPhone(checkInElderDto.getPhone());
        elder.setBirthday(checkInElderDto.getBirthday());
        elder.setAddress(checkInElderDto.getAddress());
        elder.setIdCardNationalEmblemImg(checkInElderDto.getIdCardNationalEmblemImg());
        elder.setIdCardPortraitImg(checkInElderDto.getIdCardPortraitImg());
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elderMapper.insert(elder);
        return elder;
    }
}
